from flask import Flask, request
from flask_restful import Resource, Api, fields, marshal_with
from flask_restful import reqparse

from ISPQueryInterface import *
from ISPQueryResultLoader import *
import re

app = Flask(__name__)
api = Api(app)
parser = reqparse.RequestParser()

resource_fields = {
    'task': fields.String,
    'uri': fields.Url('todo_ep')
}


class RateOfFlowQueryService(Resource):
    def get_args(self):
        return {'phone_no': dict(type='str', help='phone_no is required', required=True),
                'start_date': dict(type=str, help='start date is required', required=True),
                'end_date': dict(type=str, help='end date is required', required=True)}

    def get_type_id(self):
        return 'RateOfFlowQuery'

    def get_querier(self):
        querier = RateOfFlowQuery()
        return querier

    def query_up(self, querier, args):
        return querier.query(args['phone_no'], args['start_date'], args['end_date'])

    def rebuild_args(self):
        for arg in parser.args:
            parser.remove_argument(arg.name)
        for k, v in self.get_args().items():
            parser.add_argument(k, v)

    def get(self):
        self.rebuild_args()
        args = parser.parse_args()
        querier = self.get_querier()
        responseXml = self.query_up(querier, args)
        records = load_xml(responseXml, 'ResultDataSetConfiguration.xml', self.get_type_id())
        result = dict()
        for record in records:
            result[record.result_id] = dict(zip(filter(lambda x: not x.startswith('__'), dir(record)),
                                                map(lambda x: getattr(record, x, ''),
                                                    filter(lambda x: not x.startswith('__'), dir(record)))))
        return result


class BalanceQueryService(RateOfFlowQueryService):
    def get_args(self):
        return {'phone_no': dict(type='str', help='phone_no is required', required=True)}

    def get_type_id(self):
        return 'BalanceQuery'

    def get_querier(self):
        querier = BalanceQuery()
        return querier

    def query_up(self, querier, args):
        return querier.query(args['phone_no'])


class OrderflowPackageSetService(Resource):
    def get(self):
        order_flow = OrderFlow()
        return order_flow.get_order_flow_package_set


class OrderflowService(RateOfFlowQueryService):
    def get_args(self):
        return {'phone_no': dict(type='str', help='phone_no is required', required=True),
                'package_set': dict(type='str', help='package_set is required', required=True)}

    def get_type_id(self):
        return ''

    def get_querier(self):
        querier = OrderFlow()
        return querier

    def query_up(self, querier, args):
        result = querier.query(args['phone_no'], args['package_set'])
        print(result)
        # breakdown = re.split('\",\"', str(result).replace('{', '').replace('}', ''))
        """
        return {'checkout': re.split('\:', breakdown[0])[1], 'messg': re.split('\:', breakdown[1])[1].replace('\"', ''),
                'info': re.split('\:', breakdown[2])[1].replace('\"', '')}
                """
        return {"ok":'ok'}

    def get(self):
        querier = self.get_querier()
        self.rebuild_args()
        args = parser.parse_args()
        result = querier.query(args['phone_no'], args['package_set'])
        # 该死的电信的返回数据
        breakdown = re.split('\",\"', str(result).replace('{', '').replace('}', ''))
        return {'checkout': re.split('\:', breakdown[0])[1].replace('\"', ''), 'messg': re.split('\:', breakdown[1])[1].replace('\"', ''),
                'info': re.split('\:', breakdown[2])[1].replace('\"', '')}


api.add_resource(RateOfFlowQueryService, '/RateOfFlowService/')
api.add_resource(BalanceQueryService, '/BalanceQueryService/')
api.add_resource(OrderflowPackageSetService, '/OverflowPackageSetService/')
api.add_resource(OrderflowService, '/OrderflowService/')

if __name__ == '__main__':
    app.run(debug=True)
